import React from 'react';
import {StyleSheet, View, ScrollView} from 'react-native';
import Toast from 'react-native-easy-toast';
import * as WeChat from 'react-native-wechat';

import UShare from '../../../share/share';

import api from '../../../common/api';
import auth from '../../../common/auth';

import Commission from './commission';
import ShareText from './shareText';
import Middle from './middle';
import Bottom from './bottom';
import Header from '../../../components/header';
import SharePlatform from "../../../share/SharePlatform";

export default class extends React.Component {
    state = {
        itemId: 0,
        userInfo: {},
        couponLinkTaoToken: '',
        couponShortLinkUrl: '',
        itemInfo: {},
        imgList: [],
        shareImgUrl: '',
        shareUrl: '',
        isFetchingDetail: true
    };
    //获取详情
    getDetail = () => {
        const {itemId} = this.state;
        api({url: 'api/item/getItemDetail', data: {num_iid: itemId}, notNeedLogin: true})
            .then(data => {
                const {small_images = []} = data;
                this.setState({
                    itemInfo: data,
                    imgList: small_images.map(item => {
                        return {
                            uri: item,
                            checked: false
                        }
                    })
                });
            })
            .catch(e => {
                console.log(e);
            })
            .finally(() => {
                this.setState({
                    isFetchingDetail: false
                });
            });
    };

    //获取优惠券/淘口令
    getCouponInfo = () => {
        const {itemId} = this.state;
        api({url: 'api/ali/getCouponUrl', data: {itemid: itemId}})
            .then(data => {
                const {couponLinkTaoToken, couponShortLinkUrl, shareUrl} = data;
                this.setState({
                    couponLinkTaoToken,
                    couponShortLinkUrl,
                    shareUrl
                });
                this.getShareImg();
            })
            .catch(e => {
                this.showToast(e.msg);
            });
    };
    //获取分享图片
    getShareImg = () => {
        const {itemId, userInfo, shareUrl} = this.state;
        api({url: 'api/item/getShareImgUrl', data: {item_id: itemId, share_url: shareUrl, member_id: userInfo.id}})
            .then(data => {
                const {shareImgUrl} = data;
                this.setState({
                    shareImgUrl
                });
            })
            .catch(e => {
                console.log(e);
                this.showToast(e.msg);
            });
    };
    //切换选中图片
    checkImg = index => {
        let newArr = this.state.imgList.map((item, idx) => {
            if (index === idx) {
                return {...item, checked: !item.checked};
            }
            return item;
        });
        this.setState({
            imgList: newArr
        });
    };

    //分享图片
    share = platform => {
        const {shareImgUrl, shareUrl, itemInfo: {title}} = this.state;
        if (!shareImgUrl) {
            this.showToast('请求中，请稍后');
            return;
        }
        if (platform === SharePlatform.WECHATMOMENT) {
            UShare.share(title, title, shareUrl, shareImgUrl, platform, result => {
                alert(result);
            });
        } else {
            WeChat.isWXAppInstalled()
                .then(isInstalled => {
                    if (isInstalled) {
                        WeChat.shareToSession({
                            type: 'imageUrl',
                            title: 'web image',
                            description: 'share web image to time line',
                            mediaTagName: 'email signature',
                            messageAction: undefined,
                            messageExt: undefined,
                            imageUrl: shareImgUrl
                        })
                            .then(() => {
                                alert('分享成功');
                            })
                            .catch(e => {
                                alert('分享失败');
                                console.log(e);
                            })
                    } else {
                        this.showToast('没有安装微信软件，请您安装微信之后再试');
                    }
                });
        }
    };


    showToast = (text, time = 1000) => {
        this.refs.toast.show(text, time);
    };

    componentDidMount() {
        const {params = {}} = this.props.navigation.state;
        const itemId = params.itemId;
        auth.getUserInfo()
            .then(userInfo => {
                this.setState({
                    userInfo,
                    itemId
                }, () => {
                    this.getDetail();
                    this.getCouponInfo();
                });
            })
            .catch(() => {
                auth.goBack();
            });
    }

    render() {
        const {imgList, shareImgUrl, itemInfo, couponLinkTaoToken} = this.state;
        return (
            <View style={styles.container}>
                <Header title="创建分享"/>
                <Commission commission={itemInfo.commission}/>
                <ScrollView style={{flex: 1, padding: 10}} removeClippedSubviews={false}>
                    <ShareText itemInfo={itemInfo} couponLinkTaoToken={couponLinkTaoToken}/>
                    <Middle imgList={imgList} shareImgUrl={shareImgUrl} checkImg={this.checkImg}/>
                </ScrollView>
                <Bottom couponLinkTaoToken={couponLinkTaoToken} showToast={this.showToast} share={this.share}/>
                <Toast ref="toast" position="center"/>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: '#f6f6f5',
        flex: 1
    }
});
